package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.*;
import com.tanhua.common.pojo.*;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TestSoulService {
    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private OptionMapper optionMapper;

    @Autowired
    private UserLockMapper userLockMapper;

    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;

    @Autowired
    private QuestionnaireReportMapper questionnaireReportMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 测灵魂-问卷列表
     *
     * @return
     */
    public List<TestSoulVo> questionnaireList() {
        //拿到用户的id
        User user = UserThreadLocal.get();

        //创建要返回的对象进行填充
        List<TestSoulVo> testSoulVoList = new ArrayList<>();

        //先从问卷报告表中获取数据
        QueryWrapper<QuestionnaireReport> queryReport = new QueryWrapper<>();
        queryReport.eq("user_id",user.getId());
        List<QuestionnaireReport> questionnaireReports = this.questionnaireReportMapper.selectList(queryReport);
        if (CollUtil.isEmpty(questionnaireReports)){
            //用户是第一次使用测灵魂功能
            UserLock userLock1 = new UserLock(null,user.getId(),1L, (byte) 0,new Date(),null);
            UserLock userLock2 = new UserLock(null,user.getId(),2L, (byte) 1,new Date(),null);
            UserLock userLock3 = new UserLock(null,user.getId(),3L, (byte) 1,new Date(),null);
            this.userLockMapper.insert(userLock1);
            this.userLockMapper.insert(userLock2);
            this.userLockMapper.insert(userLock3);
        }




        //通过user_Id找到QuestionUserLock表中的user_id拿到问卷id和锁状态存到问卷vo里面
        QueryWrapper<UserLock> queryLock = new QueryWrapper<>();
        queryLock.eq("user_id",user.getId());
        List<UserLock> userLockList = this.userLockMapper.selectList(queryLock);
        for (UserLock userLock : userLockList) {
            TestSoulVo testSoulVo = new TestSoulVo();
            testSoulVo.setId(String.valueOf(userLock.getQuestionnaireId()));
            testSoulVo.setIsLock(Convert.toInt(userLock.getIsLock()));

            //不是第一次测则获取报告id
            for (QuestionnaireReport questionnaireReport : questionnaireReports) {
                if (questionnaireReport.getQuestionnaireId() == userLock.getQuestionnaireId() && userLock.getIsLock() == 0){
                    testSoulVo.setReportId(String.valueOf(questionnaireReport.getId()));
                }
            }

            testSoulVoList.add(testSoulVo);
        }

        //拿出问卷id的集合
        List<Long> questionnaireId = new ArrayList();
        for (UserLock userLock : userLockList) {
            questionnaireId.add(userLock.getQuestionnaireId());
        }

        //通过拿到的问卷id找到问题表中的数据将其返回问卷vo中
        QueryWrapper<Questionnaire> queryQuestion = new QueryWrapper<>();
        queryQuestion.in("id",questionnaireId);
        List<Questionnaire> questionnaireList = this.questionnaireMapper.selectList(queryQuestion);
        for (Questionnaire questionnaire : questionnaireList) {
            for (TestSoulVo testSoulVo : testSoulVoList) {
                if (StrUtil.equals(questionnaire.getId().toString(),testSoulVo.getId())){
                    testSoulVo.setLevel(String.valueOf(questionnaire.getLevel()));
                    testSoulVo.setCover(questionnaire.getCover());
                    testSoulVo.setName(questionnaire.getName());
                    testSoulVo.setStar(Convert.toInt(questionnaire.getStar()));
                }
            }
        }

        //把问题vo填充到问卷vo中
        for (TestSoulVo testSoulVo : testSoulVoList) {
            //根据问卷的id查询对应问卷的题干
            QueryWrapper<SoulQuestion> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("questionnaire_id",questionnaireId);
            List<SoulQuestion> soulQuestionList = this.soulQuestionMapper.selectList(queryWrapper);
            List<QuestionsVo> questionsVoList = new ArrayList<>();
            for (SoulQuestion soulQuestion : soulQuestionList) {
                //确定当问卷id和题干的问卷id一致是才可以进行填充
                if (StrUtil.equals(testSoulVo.getId(),soulQuestion.getQuestionnaireId().toString())){

                QuestionsVo questionsVo = new QuestionsVo();
                questionsVo.setId(String.valueOf(soulQuestion.getId()));
                questionsVo.setQuestion(soulQuestion.getStem());

                //根据查询到的题干的id查询对应的选项
                QueryWrapper<Option> queryOption = new QueryWrapper<>();
                queryOption.in("question_id",soulQuestion.getId());
                List<Option> options = this.optionMapper.selectList(queryOption);
                //创建选项集合
                List<OptionsVo> optionsVoList = new ArrayList<>();
                for (Option option : options) {
                    OptionsVo optionsVo = new OptionsVo();
                    optionsVo.setId(String.valueOf(option.getId()));
                    optionsVo.setOption(option.getContent());
                    optionsVoList.add(optionsVo);
                }
                questionsVo.setOptions(optionsVoList);
                questionsVoList.add(questionsVo);
            }
            testSoulVo.setQuestions(questionsVoList);
            }
        }
        return testSoulVoList;
    }

    /**
     * 测灵魂-提交问卷
     * @param answers
     * @return
     */
    public String subQuestionnaire(List<Answers> answers) {
        //遍历传入的集合
        Integer score = 0;
        String questionId = null;
        for (Answers answer : answers) {
            //查询题干id
            questionId = answer.getQuestionId();
            //选项id
            String optionId = answer.getOptionId();
            //通过题干id查询对应的选项
            QueryWrapper<Option> queryOption = new QueryWrapper<>();
            queryOption.eq("question_id",questionId);
            List<Option> options = this.optionMapper.selectList(queryOption);
            if (CollUtil.isEmpty(options)){
                return null;
            }
            for (Option option : options) {
                //当传递的选项的id数据库中的id一致时则进行查询分值
                if (StrUtil.equals(optionId,String.valueOf(option.getId()))){
                    Byte score1 = option.getScore();
                    score += score1;
                }
            }
        }
        //根据传入的题干id查询问卷id
        Long questionnaireId = this.soulQuestionMapper.selectById(questionId).getQuestionnaireId();

        //再通过查找的问卷id查询分值所在的范围
        QueryWrapper<QuestionnaireResult> queryResult = new QueryWrapper<>();
        queryResult.eq("questionnaire_id",questionnaireId);
        List<QuestionnaireResult> questionnaireResultList = this.questionnaireResultMapper.selectList(queryResult);
        //创建报告对象,将查询到的数据填充
        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        for (QuestionnaireResult questionnaireResult : questionnaireResultList) {
            //查询分值所在的区间
            String resultScore = questionnaireResult.getScope();
            String[] split = resultScore.split(",");
            //根据分值确定鉴定结果[0,20]

            if (Integer.parseInt(split[0]) <= score && Integer.parseInt(split[1]) >= score){
                questionnaireReport.setCover(questionnaireResult.getCover());
                questionnaireReport.setConclusionId(Convert.toInt(questionnaireResult.getId()));
                break;
            }
        }

        User user = UserThreadLocal.get();
        questionnaireReport.setUserId(user.getId());
        questionnaireReport.setQuestionnaireId(questionnaireId);

        //维度数据
        questionnaireReport.setAbstraction((byte) RandomUtil.randomInt(80,101));
        questionnaireReport.setExtroversion((byte) RandomUtil.randomInt(80,101));
        questionnaireReport.setJudgement((byte) RandomUtil.randomInt(80,101));
        questionnaireReport.setRetionality((byte) RandomUtil.randomInt(80,101));

        if (questionnaireId < 3){
            //开启下一阶段试题
            UserLock userLock = new UserLock();
            userLock.setIsLock((byte) 0);
            QueryWrapper<UserLock> queryLock = new QueryWrapper<>();
            queryLock.eq("questionnaire_id",questionnaireId + 1);
            this.userLockMapper.update(userLock,queryLock);
        }
        //将查询的数据插入问卷报告表中
        //如果不是第一次测试则进行修改
        //通过用户id查询报告表
        QueryWrapper<QuestionnaireReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        List<QuestionnaireReport> questionnaireReports = this.questionnaireReportMapper.selectList(queryWrapper);
        for (QuestionnaireReport report : questionnaireReports) {
            if (questionnaireReport.getQuestionnaireId() == report.getQuestionnaireId()){
                QueryWrapper<QuestionnaireReport> queryUpdate = new QueryWrapper<>();
                queryUpdate.eq("user_id",user.getId()).eq("questionnaire_id",questionnaireId);
                questionnaireReport.setUpdated(new Date());
                this.questionnaireReportMapper.update(questionnaireReport,queryUpdate);
                return String.valueOf(report.getId());
            }
        }
        //如果是则进行新增
        questionnaireReport.setCreated(new Date());
        this.questionnaireReportMapper.insert(questionnaireReport);
        return String.valueOf(questionnaireReport.getId());
    }

    /**
     *
     * @param id 结果报告id
     * @return
     */
    public TestSoulResultVo queryReport(Long id) {
        //获取当前登录用户的id
        User user = UserThreadLocal.get();
        //根据报告id查询指定的报告
        QuestionnaireReport questionnaireReport = this.questionnaireReportMapper.selectById(id);
        if (ObjectUtil.isEmpty(questionnaireReport)){
            return null;
        }
        TestSoulResultVo testSoulResultVo = new TestSoulResultVo();
        //根据查询的报告,查找对应的测试结果
        QuestionnaireResult questionnaireResult = this.questionnaireResultMapper.selectById(questionnaireReport.getConclusionId());

        testSoulResultVo.setConclusion(questionnaireResult.getContent());
        testSoulResultVo.setCover(questionnaireResult.getCover());

        //维度
        List<DimensionsVo> dimensionsVoList = new ArrayList<>();
        //通过报告表里面的ConclusionId查询数据，写维度集合里
        dimensionsVoList.add(new DimensionsVo("外向",String.valueOf(questionnaireReport.getExtroversion()) + "%"));
        dimensionsVoList.add(new DimensionsVo("判断",String.valueOf(questionnaireReport.getJudgement())+ "%"));
        dimensionsVoList.add(new DimensionsVo("抽象",String.valueOf(questionnaireReport.getAbstraction())+ "%"));
        dimensionsVoList.add(new DimensionsVo("理性",String.valueOf(questionnaireReport.getRetionality())+ "%"));

        testSoulResultVo.setDimensions(dimensionsVoList);

        //推荐相似好友
        //通过报告表根据类型查询相似用户id
        QueryWrapper<QuestionnaireReport> queryMapper = new QueryWrapper<>();
        queryMapper.eq("conclusion_id",questionnaireReport.getConclusionId());
        List<QuestionnaireReport> questionnaireReports = this.questionnaireReportMapper.selectList(queryMapper);
        List<SimilarYouVo> similarYouVos = new ArrayList<>();
        for (QuestionnaireReport report : questionnaireReports) {
            //通过查询的用户id去查询用户的具体信息
            //排除自己
            if (report.getUserId() == user.getId()){
                continue;
            }
            UserInfo userInfo = this.userInfoMapper.selectById(report.getUserId());
            SimilarYouVo similarYouVo = new SimilarYouVo();
            similarYouVo.setId(Convert.toInt(report.getUserId()));
            similarYouVo.setAvatar(userInfo.getLogo());

            similarYouVos.add(similarYouVo);
        }
        testSoulResultVo.setSimilarYou(similarYouVos);

        return testSoulResultVo;
    }
}
